package com.huonan.component.web.response.filter;

import com.mz.social.common.web.annotation.BaseResponse;
import com.mz.social.common.web.meta.ErrorCode;
import com.mz.social.common.web.model.JsonResponseWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


@ControllerAdvice(
        annotations = {BaseResponse.class}
)
public class ResponseResultHandlerAdvice implements ResponseBodyAdvice {
    private static final Logger log = LoggerFactory.getLogger(com.mz.social.common.web.filter.ResponseResultHandlerAdvice.class);

    public ResponseResultHandlerAdvice() {
    }

    public boolean supports(MethodParameter returnType, Class converterType) {
        if (log.isDebugEnabled()) {
            log.debug("returnType:" + returnType);
            log.debug("converterType:" + converterType);
        }

        return true;
    }

    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (!MediaType.APPLICATION_JSON.getType().equals(selectedContentType.getType())) {
            log.debug("body: " + body + ", selectedContentType:" + selectedContentType);
            return body;
        } else {
            return body instanceof JsonResponseWrapper ? body : JsonResponseWrapper.success(ErrorCode.OK.getCode(), ErrorCode.OK.getMessage(), body);
        }
    }
}
